package com.xyzm.mytest.nio;

import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * sink写通道
 * source读通道
 */
public class TestPipe {
    @Test
    public void test1() throws IOException {
        //获取管道
        Pipe pipe = Pipe.open();
        Pipe.SinkChannel sinkChannel = pipe.sink();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        String str="向单项管道写入数据";
        byteBuffer.put(str.getBytes());
        byteBuffer.flip();
        sinkChannel.write(byteBuffer);
        System.out.println(new String(byteBuffer.array(),0,byteBuffer.limit()));
//        byteBuffer.clear();
        //读取管道数据
        Pipe.SourceChannel sourceChannel = pipe.source();
        byteBuffer.flip();
        int read = sourceChannel.read(byteBuffer);
        System.out.println(new String(byteBuffer.array(),0,read));
        sourceChannel.close();
        sinkChannel.close();
    }
}
